package club.hicode.daydayup.redis.lettuce.fans;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import io.lettuce.core.Range;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

import java.util.Date;
import java.util.List;

/**
 * 粉丝学习
 * @author Liu Chunfu
 * @date 2018-08-27 下午3:52
 **/
public class Fans {

	private static final String KEY = "fans";

	private RedisCommands commands;

	public Fans() {
		RedisClient redisClient = RedisClient.create("redis://@localhost:6379/0");
		StatefulRedisConnection<String, String> connection = redisClient.connect();
		this.commands = connection.sync();
	}

	public void focus(String name, Date date) {
		commands.zadd(KEY, date.getTime(), name);
	}

	public void all() {
		DateTime offset = DateUtil.offset(DateUtil.date().toJdkDate(), DateField.YEAR, -1);
		List zrangebyscore = commands
				.zrangebyscore(KEY, Range.create(offset.toJdkDate().getTime(), DateUtil.date().toJdkDate().getTime()));
		if (CollectionUtil.isEmpty(zrangebyscore)) {
			return;
		}
		for (Object o : zrangebyscore) {
			System.out.println(Convert.toStr(o));
		}
	}
}
